layui.jquery(function(){
  var $ = layui.jquery
      ,layer = layui.layer
      ,form = layui.form
      ,laydate = layui.laydate;
  app.ajax = function (x) {
    $.ajax({
      url: app.host + '/diagnostic' + x.url, type: x.type, xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
      data: x.data, success: x.sucFun
    });
  };
  app.initFn = function(){
    $("body > .content").show();
    laydate.render({
      elem: '#date'
      ,min: '2017-1-1'
      ,max: '2018-12-31'
      ,done: function(value, date, endDate){
        if (value != "") {
          var _f = app.date == value;
          app.date = value;
          if (!_f) {
            app.getDiagnosisTime();
          }
        } else {
          $('.d_time').remove();
          app.class_id = 0;
        }
      }
    });
    app.ajax({url: '/grade/getGrades', type: 'GET', sucFun: function (rst) {
      app.grades = rst.gradeInfos;
      var _h = [];
      for (var i = 0; i < app.grades.length; i++) {
        _h.push('<option value="' + app.grades[i].id + '">' + app.grades[i].grade + '</option>');
      }
      // app.gradesHtml = _h.join("");
      $('.gradeSelect').append(_h.join(""));
      form.render('select');
    }});
    app.ajax({url: '/course/getCourses', type: 'GET', sucFun: function (rst) {
      app.courses = rst.courseInfos;
      var _h = [];
      for (var i = 0; i < app.courses.length; i++) {
        _h.push('<option value="' + app.courses[i].id + '">' + app.courses[i].course + '</option>');
      }
      // app.coursesHtml = _h.join("");
      $('.courseSelect').append(_h.join(""));
      form.render('select');
    }});
    $('#getCode').click(function () {
      var phone = $('[name=phone]').val();
      if (/^1[0-9]{10}$/.test(phone)) {
        layer.open({type:3});
        $.ajax({
          url: app.host + '/Lecture/Datas/sms', type: 'POST', xhrFields: { withCredentials: true }, crossDomain: true,
          data:{ phone: phone }, dataType: 'json',
          type:'POST',
          success: function(rst){
            layer.closeAll('loading');
            if(rst && rst.code){
              layer.msg("验证码发送成功");
              app.code = rst.code;
              app.phone = phone;
              app.time = 60;
              $('#getCode').hide().next().show();
              app.intervalId = setInterval(function () {
                if (app.time == 0) {
                  $('#second i').text('60').parent().hide().prev().show();
                  clearInterval(app.intervalId);
                }else {
                  $('#second i').text(--app.time);
                }
              }, 990);
            }else {
              layer.msg("发送失败,请稍后再试");
            }
          }
        });
      }else {
        layer.msg("请输入正确的手机号码");
      }
    });
    form.on('select', function(data){
      var _f = true;
      if (data.elem.id == 'grade') {
        _f = data.value == app.g_id;
        app.g_id = data.value;
        app.gradeName = $(data.othis[0]).find('input').val();
      } else if (data.elem.id == 'course') {
        _f = data.value == app.c_id;
        app.c_id = data.value;
        app.courseName = $(data.othis[0]).find('input').val();
      }
      if (!_f) {
        app.getDiagnosisTime();
      }
    });
    form.on('radio', function(data){
      if (data.elem.name=='time') {
        app.class_id = data.value;
        app.timeText = $(data.othis[0]).find('span').text();
      }
    });
    app.getDiagnosisTime = function () {
      if (app.code != $('[name=code]').val()) {
        layer.msg('验证码不正确');
      } else if (!app.g_id) {
        // layer.msg('请选择年级');
      } else if (!app.c_id) {
        // layer.msg('请选择科目');
      // } else if (!(/^1[0-9]{10}$/.test(app.phone))) {
      //   layer.msg('请输入正确的手机号码');
      } else if (!app.date) {

      } else {
        app.ajax({url: '/Index/getClassInfo', type: 'POST', data: {phone: app.phone, g_id: app.g_id, c_id: app.c_id, time: app.date}, sucFun: function (rst) {
          var clas = rst.classInfos;
          $('.d_time').remove();
          var _h = [];
          for (var i = 0; i < clas.length; i++) {
            var title = app.getTimeRange(Number(clas[i].start_time+'000'), Number(clas[i].end_time+'000'));
            _h.push('<div class="d_time layui-input-block">'
                    + '<input type="radio"' + (clas[i].signup_status==1?'':' disabled') + ' name="time" value="' + clas[i].id + '" title="' + title + '">'
                  + '</div>');
          }
          $('#diagnosisTime').append(_h.join(''));
          form.render('radio');
          if (_h.length == 0) {
            $('#diagnosisTime').append('<div class="d_time layui-input-block"><div style="color:#999">当天没有课程,请选择其它日期~~</div></div>')
          }
          app.class_id = 0;
        }});
      }
    }
    $('[name=code]').bind('input propertychange', function() {
        if ($(this).val() == app.code) {
          $(".codeCtrl").removeClass("noCode");
          $("[name=qq],#date,#course,#grade").removeAttr("disabled");
          form.render('select');
        } else {
          $(".codeCtrl").addClass("noCode");
          $("[name=qq],#date,#course,#grade").attr("disabled",true);
          form.render('select');
        }
    });
    $('#confirm').click(function () {

      var data = {
        name: $('[name=username]').val(),
        phone: app.phone,
        qq: $('[name=qq]').val(),
        g_id: app.g_id,
        c_id: app.c_id,
        class_id: app.class_id
      }
      if (!data.class_id) {
        layer.msg('请选择诊断时间');
      } else if (data.name.length < 2) {
        layer.msg('请输入真实姓名');
      } else if (data.qq.length < 4) {
        layer.msg('请输入QQ号码');
      } else {
        layer.confirm('确认提交？', {
          btn: ['确定','取消'] //按钮
        }, function(){
          app.ajax({url: '/Index/saveSignupInfo', type: 'POST', data: data, sucFun: function (rst) {
            if (rst.code == 1000) {
              $('.d_time').remove();
              app.class_id = 0;
              layer.open({
                type: 1
                ,offset: 'auto'
                ,id: 'layerDemo' //防止重复弹出
                ,content: '<div style="padding: 20px 20px;">您已成功报名'
                          + app.gradeName + app.courseName + app.date.substring(0,4) + '年' + app.timeText + '的活动'
                        + '</div>'
                ,btn: '知道了'
                ,btnAlign: 'c' //按钮居中
                ,shade: 1 //不显示遮罩
                ,yes: function(){
                  layer.closeAll();
                }
              });
            } else {
              layer.msg(rst.message);
            }
          }});
        });
      }
    });
  };
  try {

    app.initFn();

  } catch (e) {
    console.log(e);
  } finally {

  }
});
